/**
 *
 */

package com.kjcxlab.avcviewer.network;

import com.kjcxlab.avcviewer.player.IntegrateListener;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * @author efhkklm
 */
public class UdpReceiver {

    private DatagramSocket mSocket = null;
    private byte[] recieveBuf = null;
    private DatagramPacket mPacket = null;
    private IntegrateListener mRtpListener = null;

    public UdpReceiver(int localPort, IntegrateListener listener) {
        try {
            mRtpListener = listener;
            mSocket = new DatagramSocket(null);
            mSocket.setReuseAddress(true);
            mSocket.bind(new InetSocketAddress(localPort));
            recieveBuf = new byte[1024 * 4];
            mPacket = new DatagramPacket(recieveBuf, recieveBuf.length);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        new Thread(new Receiver()).start();
    }

    class Receiver implements Runnable {

        @Override
        public void run() {
            while (true) {

                int length = 0;
                try {
                    mSocket.receive(mPacket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if ((length = mPacket.getLength()) > 0) {
                    byte[] buf = new byte[length];
                    System.arraycopy(mPacket.getData(), mPacket.getOffset(), buf, 0, length);
                    mRtpListener.integrateOneFrame(buf);
                }
            }
        }
    }

    @Override
    protected void finalize() {
        mSocket.close();
    }

}
